<template>
  <div class="achievement-container">
    <van-notice-bar scrollable>
      *根据学校规定，完成以下信息填写才可以提交申请！
    </van-notice-bar>

    <!-- 个人信息卡片 -->
    <div class="user-card">
      <div class="avatar-container">
        <img :src="userInfo.userInfo.userImage" alt="用户头像" class="user-avatar" />
      </div>
      <div class="user-info">
        <div class="info-item">
          <span class="info-label">姓名：</span>
          <span class="info-value">{{ userInfo.userInfo.userName }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">工号：</span>
          <span class="info-value">{{ userInfo.userInfo.userNumber }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">职务：</span>
          <span class="info-value">
            <template v-if="userInfo.userInfo.userType == 1">领导</template>
            <template v-else-if="userInfo.userInfo.userType == 2">辅导员</template>
            <template v-else-if="userInfo.userInfo.userType == 3">教师</template>
          </span>
        </div>
        <div class="info-item">
          <span class="info-label">部门：</span>
          <span class="info-value">{{ userInfo.userInfo.department }}</span>
        </div>
      </div>
    </div>

    <!-- 教师工号输入 -->
    <van-cell-group inset style="margin: 0;">
      <van-field
          required
          v-model="targetTeacherNumber"
          label="教师工号"
          placeholder="请输入对方教师工号"
          type="number"
      />
    </van-cell-group>

    <!-- 结对类型选择 -->
    <van-field
        v-model="pairType"
        is-link
        readonly
        required
        label="结队类型"
        placeholder="选择类型"
        @click="showPicker1 = true"
        style="margin-top: 20px"
    />
    <van-popup v-model:show="showPicker1" destroy-on-close round position="bottom">
      <van-picker
          :model-value="pickerValue_pairType"
          :columns="pairType_list"
          @cancel="showPicker1 = false"
          @confirm="onConfirm_pairType"
      />
    </van-popup>

    <!-- 申请说明 -->
    <div class="add_xq">
      <van-cell-group>
        <van-field
            required
            type="textarea"
            v-model="description"
            label="申请说明"
            placeholder="请填写申请说明："
            rows="5"
            autosize
            maxlength="1000"
            show-word-limit
            style="margin-top: 20px"
        />
      </van-cell-group>

      <!-- 文件上传 -->
      <div class="upload-section">
        <div class="upload-title">上传图片（可选，最多5张）</div>
        <van-uploader
            v-model="fileList"
            multiple
            :max-count="5"
            :after-read="afterRead"
            class="uploader"
        >
          <template #preview-cover="{ file }">
            <div class="preview-cover">
              <div v-if="file.status === 'uploading'" class="upload-status uploading">
                {{ file.message }}
              </div>
              <div v-if="file.status === 'failed'" class="upload-status failed">
                {{ file.message }}
              </div>
              {{ file.name }}
            </div>
          </template>
        </van-uploader>
      </div>
    </div>

    <!-- 提交按钮 -->
    <div class="dowm_bt">
      <van-button
          class="ljtj"
          @click="xq_submit"
          :loading="submitting"
          :disabled="submitting"
      >
        {{ submitting ? '提交中...' : '立即提交' }}
      </van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useUserStore } from '../../Store/modules/userinfo/UserInfo.ts'
import { showFailToast, showSuccessToast, showConfirmDialog } from "vant";
import { applyForPairUsingPost } from '../../Api/jiaoshijiedui.ts'
import { uploadUsingPost } from '../../Api/wenjianshangchuanmokuai.ts'
import type {Numeric} from "vant/es/utils";
import router from "../../Router";

const userInfo = useUserStore()

// 表单数据
const description = ref("")
const targetTeacherNumber = ref("")
const fileList = ref<Array<{file?: File, url?: string, name?: string, status?: string, message?: string}>>([])

// 结对类型相关
const pairType_list = [
  { text: '老带新帮扶', value: 1 },
  { text: '科级干部结队', value: 2 },
  { text: '新老师导师指导', value: 3 },
];
const pairType = ref('');
const showPicker1 = ref(false);
const pickerValue_pairType = ref<Numeric[]>([]);

// 状态
const submitting = ref(false)

// 文件上传处理
const afterRead = async (file: any) => {
  try {
    const files = Array.isArray(file) ? file : [file]

    for (const f of files) {
      f.status = 'uploading'
      f.message = '上传中...'

      // 检查文件大小
      if (f.file && f.file.size > 5 * 1024 * 1024) {
        throw new Error(`文件 ${f.file.name} 大小超过5MB限制`)
      }

      // 上传文件
      const response = await uploadUsingPost({}, f.file)
      if (response.data.code === 0 && response.data.data) {
        f.status = 'done'
        f.url = response.data.data
        f.message = '上传成功'
      } else {
        throw new Error(response.data.message || '上传失败')
      }
    }
  } catch (error: any) {
    file.status = 'failed'
    file.message = error.message || '上传失败'
    showFailToast(file.message)
  }
}

// 结对类型选择确认
const onConfirm_pairType = ({ selectedValues, selectedOptions }: any) => {
  showPicker1.value = false
  pickerValue_pairType.value = selectedValues
  pairType.value = selectedOptions[0].text
}

// 表单验证
const validateForm = () => {
  const errors: string[] = []

  if (!targetTeacherNumber.value.trim()) errors.push('请输入对方教师工号')
  if (!pickerValue_pairType.value.length) errors.push('请选择结对类型')
  if (!description.value.trim()) errors.push('请填写申请说明')

  // 验证工号格式（假设工号为6-10位数字）
  if (!/^\d{6,10}$/.test(targetTeacherNumber.value.trim())) {
    errors.push('教师工号应为6-10位数字')
  }

  return errors
}

// 提交表单
async function xq_submit() {
  // 验证表单
  const errors = validateForm()
  if (errors.length > 0) {
    showFailToast(errors[0])
    return
  }
  if (targetTeacherNumber.value === userInfo.userInfo.userNumber){
    showFailToast('不能和自己结队！')
    return
  }

  try {
    // 确认对话框
    await showConfirmDialog({
      title: '确认提交',
      message: '确定要提交结对申请吗？'
    })

    submitting.value = true

    // 1. 上传文件（如果有）
    let photoPath = ''
    if (fileList.value.length > 0) {
      showSuccessToast('正在上传文件...')

      // 上传所有新文件
      const uploadPromises = fileList.value
          .filter(file => file.file && !file.url)
          .map(file => uploadFile(file))

      try {
        const uploadedUrls = await Promise.all(uploadPromises)
        // 使用第一个上传成功的文件URL
        if (uploadedUrls.length > 0) {
          photoPath = uploadedUrls[0]
        }
      } catch (error) {
        console.error('文件上传失败:', error)
        throw new Error('文件上传失败，请重试')
      }

      // 如果已经有URL（之前上传过的）
      if (!photoPath) {
        const existingFile = fileList.value.find(f => f.url)
        if (existingFile) {
          photoPath = existingFile.url
        }
      }
    }

    // 2. 准备提交数据
    const submitData = {
      targetTeacherNumber: targetTeacherNumber.value.trim(),
      pairType: pickerValue_pairType.value[0], // 使用value值
      description: description.value.trim(),
      photoPath: photoPath
    }

    console.log('提交数据:', submitData)

    // 3. 提交表单
    showSuccessToast('正在提交申请...')
    const response = await applyForPairUsingPost(submitData)

    if (response.data.code === 0) {

      // 清空表单
      resetForm()
      setTimeout(() => {
        showSuccessToast('提交成功！')
      }, 1000)
      // 跳转到首页
      router.push('/cqust/index')
    } else {
      throw new Error(response.data.message || '提交失败')
    }
  } catch (error: any) {
    if (error.message !== 'cancel') {
      console.error('提交失败:', error)
      showFailToast(error.message || '提交过程中出错')
    }
  } finally {
    submitting.value = false
  }
}

// 上传单个文件
const uploadFile = async (fileItem: { file?: File }, retries = 3) => {
  if (!fileItem.file) throw new Error('无效的文件')

  let lastError

  for (let i = 0; i < retries; i++) {
    try {
      const response = await uploadUsingPost({}, fileItem.file)

      if (response.data.code === 0 && response.data.data) {
        return response.data.data
      } else {
        lastError = new Error(response.data.message || '文件上传失败')
      }
    } catch (error) {
      lastError = error
    }

    if (i < retries - 1) {
      await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)))
    }
  }

  throw lastError
}

// 重置表单
const resetForm = () => {
  targetTeacherNumber.value = ''
  pickerValue_pairType.value = []
  pairType.value = ''
  description.value = ''
  fileList.value = []
}
</script>

<style scoped>
/* 保持之前的样式不变 */
.achievement-container {
  height: 100vh;
  overflow-y: auto;
  padding: 10px;
}

.user-card {
  display: flex;
  background-color: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.avatar-container {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 16px;
  border: 2px solid #f0f0f0;
}

.user-avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-info {
  flex: 1;
  margin-left: 20px;
}

.info-item {
  margin-bottom: 8px;
  display: flex;
}

.info-label {
  color: #888;
  width: 60px;
  font-size: 14px;
}

.info-value {
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

.add_xq {
  width: 100%;
  margin: 12px auto;
  border-radius: 15px;
  background-color: #fbfbfc;
}

.dowm_bt {
  width: 90%;
  margin: 20px auto;
  text-align: center;
}

.ljtj {
  width: 40%;
  background-color: rebeccapurple;
  border-radius: 20px;
  color: white;
}

.upload-section {
  background-color: white;
  border-radius: 12px;
  padding: 16px;
}

.upload-title {
  color: #666;
  font-size: 14px;
  margin-bottom: 12px;
}

.uploader {
  margin-top: 8px;
}

.preview-cover {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 4px;
  font-size: 12px;
  color: white;
  background-color: rgba(0, 0, 0, 0.5);
}

.upload-status {
  text-align: center;
  padding: 2px;
  border-radius: 4px;
  margin: 2px;
}

.upload-status.uploading {
  background-color: #1989fa;
}

.upload-status.failed {
  background-color: #ee0a24;
}
</style>